#include "../UDP_Server/UDP_Server.h"

//服务端处理信息，将字符换变为大写
void StrToUpper(char* str,int len)
{
  for(int i=0;i<len ;i++)
  {
    str[i]=toupper(str[i]);
  }
}
//服务端处理信息，将字符换变为小写
void StrToLower(char* str,int len)
{
  for(int i=0;i<len ;i++)
  {
    str[i]=tolower(str[i]);
  }
}

void UDP_ServerAPI()
{
  //加载Windows环境
  WORD ver = MAKEWORD(2, 2);
  WSADATA dat;
  WSAStartup(ver, &dat);
  
  //创建socket
  SOCKET Server_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  sockaddr_in Server_sin = {};
  Server_sin.sin_family = AF_INET;
  Server_sin.sin_port = htons(SERVER_PORT);
  //Server_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //INADDR_ANY为默认地址
  //将十进制SERVER_IP转化为二进制保存至Server_sin.sin_addr中
  inet_pton(AF_INET, SERVER_IP, &Server_sin.sin_addr);

  //调用bind，将服务端本地地址到socket上
  if (SOCKET_ERROR == bind(Server_sock, (sockaddr*)&Server_sin, sizeof(Server_sin)))
  {
    printf("Bind failed!!!\n");
  }
  else {
    printf("Bind successful...\n");
  }

  //调用accept接收客户端连接申请，并将客户端信息保存至Client_sin中
  sockaddr_in Client_sin = {};
  char IPdotdec[20];
  int nAddrLen = sizeof(sockaddr_in);

  char recvBuf[1024] = {};
  while (true)
  {
    //调用recv函数接收客户端发送的信息
    int nLen = recvfrom(Server_sock, recvBuf, 1024, 0,(SOCKADDR*) &Client_sin, &nAddrLen);
    if (nLen <= 0) {
      printf("Recv client's message failed!!!\n");
      break;
    }
    printf("Recv successful...");
    recvBuf[nLen]='\0';
    if(strcmp(recvBuf,"bye")==0)
    {
      printf("Client close!!!");      
      closesocket(Server_sock);  
      return ;
    }
    else
    {
      printf("Recv message sucessful from %s ...\n Message:%s\n", inet_ntoa(Client_sin.sin_addr), recvBuf);
    }
    StrToLower(recvBuf,strlen(recvBuf));

    sendto(Server_sock,recvBuf, strlen(recvBuf), 0, (SOCKADDR*)&Client_sin, sizeof(SOCKADDR)); 

    memset(recvBuf, 0, sizeof(recvBuf));
  }

  //当客户端断开连接后，会关闭客户端
  closesocket(Server_sock);
  //
  WSACleanup();
  printf("Sever closed ...");
}